import 'dart:math';

import 'package:flutter/material.dart';
import 'package:eshi/app/shi/data/History.dart';
import 'package:eshi/app/shi/data/HistoryPoint.dart';
import 'package:eshi/app/shi/event/TAxisEvent.dart';
import 'package:eshi/app/shi/others.dart';
import 'package:eshi/app/shi/tabs.dart';
import 'package:eshi/app/shi/taxis/CurrentPointCursor.dart';
import 'package:eshi/app/shi/taxis/TimelinePainter.dart';
import 'package:eshi/app/shi/tools.dart';

/// time axis 时间轴 
/// 根据屏幕方向适配 竖屏方屏（左边）或横屏（底部）
/// 包括3个部分 1 带刻度的线 2 标记点 3 移动轴
/// 入参 范围（总长度单刻度），默认值，  
///  


class TimeAxisWidget extends StatefulWidget{
  History data;
  var posTime = 0;
  late DateTime startTime;
  late DateTime endTime;
  late List<HistoryPoint> events;
  int index=0;           //当前朝代序号


  TimeAxisWidget(this.data, {super.key}){
      startTime = DateTime(data.startTime);
      endTime = DateTime(data.endTime);
      events = data.data;
  }
  static TimeAxisState of(BuildContext context) {
      final TimeAxisState? result = context.findRootAncestorStateOfType<TimeAxisState>();
      if (result != null) {
        return result;
      }
      throw FlutterError.fromParts(<DiagnosticsNode>[]);
  }

  @override
  State<StatefulWidget> createState() => TimeAxisState();
  /// 根据朝代返回距离  
  double handleOffsetLen(double length,int index) {
    final double totalSeconds = endTime.difference(startTime).inSeconds.toDouble();
    final double pixelsPerSecond = totalSeconds > 0 ? (length / totalSeconds) : 0;
    if(index>=events.length) return 0;
    var eventTime = DateTime(events[index].startTime);
    return  eventTime.difference(startTime).inSeconds * pixelsPerSecond;
  }
  /// 根据坐标位置获取point
  HistoryPoint? handleTap(double length,double tapPosition) {
    // 计算点击位置对应的时间
    final double totalSeconds = endTime.difference(startTime).inSeconds.toDouble();
    final double pixelsPerSecond = totalSeconds > 0 ? (length / totalSeconds) : 0;
    
    // 查找距离点击位置最近的事件
    // const double tolerance = 15.0; // 点击容差范围（像素）
    HistoryPoint? closestPoint;
    // double minDistance = double.infinity;
    for (final event in events) {
      var eventTime = DateTime(event.startTime);
      final double start = eventTime.difference(startTime).inSeconds * pixelsPerSecond;
      final double end = DateTime(event.endTime).difference(startTime).inSeconds * pixelsPerSecond;
      if(start<=tapPosition && end > tapPosition){
        closestPoint = event;
        break;
      }
      if(event.startTime==event.endTime && tapPosition<start){
        closestPoint = events[events.indexOf(event)-1];
        break;
      }
    }

    if(closestPoint != null){
      index = closestPoint.index;
    }
    return closestPoint;
  }
}

class TimeAxisState extends State<TimeAxisWidget> with TAxisEvent{
  Offset currentPos = Offset(0, 0);
  HistoryPoint? currentPoint;
  var isTVisible=false;
  late double length;
  double _offsetY = 0.0; // 垂直偏移量
  bool isHorizontal=true;
  tabsState? tabState;

  void showTimeLine(){
    var posLength = widget.handleOffsetLen(length,widget.index);
    currentPos = isHorizontal?  Offset(posLength,0) : Offset(0,posLength);
    isTVisible = true;
  }
  /// 通过时间轴的单击选择时间点 
  void upPos(Offset pos){
     setState(() {
          currentPos = pos;
     });
     var point = widget.handleTap(length,isHorizontal ? pos.dx:pos.dy);
     if(point!=null && point!=currentPoint){
        onTimeLineClick(point);
     }
  }
  /// 通过上下滑动更新朝代
  void upIndex(int add){
    //不知道为什么 index明明被修改了 可这里总是0 先兼容修复一下吧 
    if(widget.index ==0 ) widget.index = currentPoint!.index;
    if(widget.events.length==1){
      tabState?.onChangeTab(add);
      setState(() {
        _offsetY =0;  
      });
      return;
    }
    widget.index+=add;
    
    if(widget.index<0){
        widget.index=0;
        // onSearch().then((p){
        //   tabState
        //     ?..searchCount = p.count
        //     ..searchIndex = 0
        //     ..searchKey = p.key;
        //   onSearchIndex(p.key, state: tabState);
        // });
    }else if(widget.index>widget.events.length-1){
      widget.index+=-add;
      // showTimeLine();
    }else{
      onPageDraw(widget.events[widget.index]);
      // isTVisible = false;
    }

    setState(() {
      _offsetY =0;  
    });
  }


   Widget timeLine(){
    const double width = 100;
    var [w,h] = isHorizontal ? [length,width] : [width,length];
    return  Container(
        width: w,
        height: h,
        color: Colors.blue,
        child:  Stack(children: [
           GestureDetector(
              onPanUpdate: (details) {
                  upPos(details.localPosition);
              },
              onPanEnd: (details) {
                  upPos(details.localPosition);
                  // isTVisible = false;
                  handleWillPop();
              },
              child:CustomPaint(
                size: Size(w,h),
                painter: TimelinePainter(
                  startTime: widget.startTime,
                  endTime: widget.endTime,
                  events: widget.events,
                ),
              ), 
              // Transform.rotate(
              //   angle: 3.14 / 2, child:  UnconstrainedBox(child: ),
          ),
          CurrentPointCursor(currentPos,isHorizontal),
      ])
      );
  }


  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    length = max(size.width,size.height)*0.95;
    isHorizontal = size.width>size.height;
    if(currentPoint==null || !widget.events.contains(currentPoint!)){
        currentPoint = widget.data.defaultPoint;
    }
    
    return Expanded(
      child: Stack(
            children: [
              Positioned.fill(child: WillPopScope (
                  // 拦截返回事件
                  onWillPop: handleWillPop,
                  child: Text("hi"))
              ),
              GestureDetector(
                  onVerticalDragUpdate: (details) {   //上下滑动
                      _offsetY += details.delta.dy;
                  },
                  onVerticalDragEnd: (details) {      //停止滑动的时候切换朝代
                      if(_offsetY.abs()>50) upIndex(_offsetY>0 ? -1:1);  
                  },
                  child:  Transform.translate(
                    offset: Offset(0, _offsetY),      // 应用偏移量
                    child: tabsWidget(currentPoint!, onStateReady: (state) {
                        tabState = state; // 保存子组件状态
                    }),
                )
              ),
              Visibility(
                visible: isTVisible, //
                child: Positioned.fill( //指定全屏
                    child: Stack(
                        children: [
                          GestureDetector(
                            onTap:(){
                              setState((){
                                // isTVisible = false;
                                handleWillPop();
                              });
                            },
                            child:  Opacity(
                                opacity:0.7,
                                child:   Container(
                                  color: Colors.blueGrey,
                                )
                            ),
                          ),
                          Align(
                            alignment: isHorizontal? Alignment.topCenter: Alignment.centerLeft,
                            child: OthersWidget(isHorizontal,widget.data.id)
                          ),
                          Align(
                            alignment: Alignment.center,
                            child:timeLine()
                          ),
                          Align(
                            alignment: Alignment.bottomRight,
                            child: tools(isHorizontal,widget.data)
                          )
                        ]  
                    )
                  )
              )
            ]
        ),
    );
  }
}